package com.houkunlin.knife4j;

import com.github.xiaoymin.knife4j.spring.extension.OpenApiExtensionResolver;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Controller;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * @author HouKunLin
 */
@ConditionalOnClass(OpenApiExtensionResolver.class)
@Configuration
@Import(BeanValidatorPluginsConfiguration.class)
@AllArgsConstructor
public class SwaggerConfiguration {
    private static final Logger logger = LoggerFactory.getLogger(SwaggerConfiguration.class);
    private final OpenApiExtensionResolver openApiExtensionResolver;

    @Bean("defaultApi2")
    public Docket defaultApi2(List<DocketCustomizer> customizers) {
        final Docket docket = new Docket(DocumentationType.SWAGGER_2)
                // .host("https://www.baidu.com")
                .groupName("default")
                .apiInfo(apiInfo())
                // 修正Byte转string的Bug
                .directModelSubstitute(Byte.class, Integer.class);
        customizers.forEach(docketCustomizer -> docketCustomizer.customize(docket));
        return docket
                .select()
                // .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .apis(requestHandler -> {
                    Class<?> declaringClass = requestHandler.declaringClass();
                    if (declaringClass != null && AbstractErrorController.class.isAssignableFrom(declaringClass)) {
                        return false;
                    }
                    final Optional<Controller> controller = requestHandler.findControllerAnnotation(Controller.class);
                    return controller.isPresent();
                })
                .build()
                //赋予插件体系
                .extensions(openApiExtensionResolver.buildExtensions(docket.getGroupName()));
    }

    @Bean("defaultApi3")
    public Docket defaultApi3(List<DocketCustomizer> customizers) {
        final Docket docket = new Docket(DocumentationType.SWAGGER_2)
                // .host("https://www.baidu.com")
                .groupName("监控状态接口 Actuator")
                .apiInfo(apiInfo())
                // 修正Byte转string的Bug
                .directModelSubstitute(Byte.class, Integer.class);
        customizers.forEach(docketCustomizer -> docketCustomizer.customize(docket));
        return docket
                .select()
                // .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .apis(requestHandler -> {
                    Class<?> declaringClass = requestHandler.declaringClass();
                    if (declaringClass != null && AbstractErrorController.class.isAssignableFrom(declaringClass)) {
                        return false;
                    }
                    final Set<String> pathMappings = requestHandler.key().getPathMappings();
                    for (final String pathMapping : pathMappings) {
                        if (pathMapping.startsWith("/actuator/")) {
                            return true;
                        }
                    }
                    return declaringClass != null && declaringClass.getName().startsWith("org.springframework.boot.actuate.endpoint");
                })
                .build()
                //赋予插件体系
                .extensions(openApiExtensionResolver.buildExtensions(docket.getGroupName()));
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //.title("swagger-bootstrap-ui-demo RESTful APIs")
                // .description("# swagger-bootstrap-ui-demo RESTful APIs")
                // .termsOfServiceUrl("http://www.houkunlin.com/")
                // .contact(new Contact("", "", ""))
                // .version("1.0")
                .build();
    }
}
